/*
 * This file is part of CompetitionGenerator.
 * CompetitionGenerator is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * CompetitionGenerator is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with CompetitionGenerator. If not, see <http://www.gnu.org/licenses/>.
 */
package competitiongenerator;

import java.io.FileNotFoundException;
import java.util.logging.Level;
import org.jdesktop.application.Action;
import org.jdesktop.application.ResourceMap;
import org.jdesktop.application.SingleFrameApplication;
import org.jdesktop.application.FrameView;
import org.jdesktop.application.TaskMonitor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.util.logging.Logger;
import javax.swing.Timer;
import javax.swing.Icon;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.table.TableColumn;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;

/**
 * The application's main frame.
 * @author Praiet
 */
public class CompetitionGeneratorView extends FrameView {

    private final Logger logger = Logger.getLogger(CompetitionGeneratorView.class.getName());

    /**
     * Constructor.
     * @param app the app.
     */
    public CompetitionGeneratorView(SingleFrameApplication app) {
        super(app);
        logger.setLevel(CompetitionGeneratorApp.level);
        initComponents();

        if (CompetitionGeneratorApp.logger.isLoggable(Level.INFO)) {
            CompetitionGeneratorApp.logger.log(Level.INFO, "Components initiated.");
        }


        // status bar initialization - message timeout, idle icon and busy animation, etc
        ResourceMap resourceMap = getResourceMap();
        int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout");
        messageTimer = new Timer(messageTimeout, new ActionListener() {

            /**
             * Action Performed.
             */
            @Override
            public void actionPerformed(ActionEvent e) {
                statusMessageLabel.setText("");
            }
        });
        messageTimer.setRepeats(false);
        int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate");
        for (int i = 0; i < busyIcons.length; i++) {
            busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]");
        }
        busyIconTimer = new Timer(busyAnimationRate, new ActionListener() {

            /**
             * Action Performed.
             */
            @Override
            public void actionPerformed(ActionEvent e) {
                busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
                statusAnimationLabel.setIcon(busyIcons[busyIconIndex]);
            }
        });
        idleIcon = resourceMap.getIcon("StatusBar.idleIcon");
        statusAnimationLabel.setIcon(idleIcon);
        progressBar.setVisible(false);

        // connecting action tasks to status bar via TaskMonitor
        TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext());
        taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() {

            /**
             * Internal function.
             */
            @Override
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                String propertyName = evt.getPropertyName();
                if ("started".equals(propertyName)) {
                    if (!busyIconTimer.isRunning()) {
                        statusAnimationLabel.setIcon(busyIcons[0]);
                        busyIconIndex = 0;
                        busyIconTimer.start();
                    }
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(true);
                } else if ("done".equals(propertyName)) {
                    busyIconTimer.stop();
                    statusAnimationLabel.setIcon(idleIcon);
                    progressBar.setVisible(false);
                    progressBar.setValue(0);
                } else if ("message".equals(propertyName)) {
                    String text = (String) (evt.getNewValue());
                    statusMessageLabel.setText((text == null) ? "" : text);
                    messageTimer.restart();
                } else if ("progress".equals(propertyName)) {
                    int value = (Integer) (evt.getNewValue());
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(false);
                    progressBar.setValue(value);
                }
            }
        });
    }

    /**
     * Action.
     */
    @Action
    public void showAboutBox() {
        if (aboutBox == null) {
            JFrame mainFrame = CompetitionGeneratorApp.getApplication().getMainFrame();
            aboutBox = new CompetitionGeneratorAboutBox(mainFrame);
            aboutBox.setLocationRelativeTo(mainFrame);
        }
        CompetitionGeneratorApp.getApplication().show(aboutBox);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        mainPanel = new javax.swing.JPanel();
        TabbedPane = new javax.swing.JTabbedPane();
        CompetitorsPane = new javax.swing.JScrollPane();
        ExcelTable = new javax.swing.JTable();
        FightsPane = new javax.swing.JScrollPane();
        menuBar = new javax.swing.JMenuBar();
        javax.swing.JMenu fileMenu = new javax.swing.JMenu();
        newMenuItem = new javax.swing.JMenuItem();
        openMenuItem = new javax.swing.JMenuItem();
        cleanTableMenuItem = new javax.swing.JMenuItem();
        javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem();
        jMenuItem1 = new javax.swing.JMenuItem();
        jMenuItem2 = new javax.swing.JMenuItem();
        jMenuItem3 = new javax.swing.JMenuItem();
        jMenuItem4 = new javax.swing.JMenuItem();
        javax.swing.JMenu helpMenu = new javax.swing.JMenu();
        javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem();
        statusPanel = new javax.swing.JPanel();
        javax.swing.JSeparator statusPanelSeparator = new javax.swing.JSeparator();
        statusMessageLabel = new javax.swing.JLabel();
        statusAnimationLabel = new javax.swing.JLabel();
        progressBar = new javax.swing.JProgressBar();

        mainPanel.setName("mainPanel"); // NOI18N

        TabbedPane.setEnabled(false);
        TabbedPane.setName("TabbedPane"); // NOI18N

        CompetitorsPane.setEnabled(false);
        CompetitorsPane.setName("CompetitorsPane"); // NOI18N

        ExcelTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        ExcelTable.setEnabled(false);
        ExcelTable.setName("ExcelTable"); // NOI18N
        CompetitorsPane.setViewportView(ExcelTable);

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(competitiongenerator.CompetitionGeneratorApp.class).getContext().getResourceMap(CompetitionGeneratorView.class);
        TabbedPane.addTab(resourceMap.getString("CompetitorsPane.TabConstraints.tabTitle"), resourceMap.getIcon("CompetitorsPane.TabConstraints.tabIcon"), CompetitorsPane); // NOI18N

        FightsPane.setEnabled(false);
        FightsPane.setName("FightsPane"); // NOI18N
        TabbedPane.addTab(resourceMap.getString("FightsPane.TabConstraints.tabTitle"), resourceMap.getIcon("FightsPane.TabConstraints.tabIcon"), FightsPane); // NOI18N

        javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
        mainPanel.setLayout(mainPanelLayout);
        mainPanelLayout.setHorizontalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(TabbedPane, javax.swing.GroupLayout.DEFAULT_SIZE, 551, Short.MAX_VALUE)
        );
        mainPanelLayout.setVerticalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(TabbedPane, javax.swing.GroupLayout.DEFAULT_SIZE, 391, Short.MAX_VALUE)
        );

        menuBar.setName("menuBar"); // NOI18N

        fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N
        fileMenu.setName("fileMenu"); // NOI18N

        newMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_N, java.awt.event.InputEvent.CTRL_MASK));
        newMenuItem.setIcon(resourceMap.getIcon("newMenuItem.icon")); // NOI18N
        newMenuItem.setText(resourceMap.getString("newMenuItem.text")); // NOI18N
        newMenuItem.setName("newMenuItem"); // NOI18N
        fileMenu.add(newMenuItem);

        openMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O, java.awt.event.InputEvent.CTRL_MASK));
        openMenuItem.setIcon(resourceMap.getIcon("openMenuItem.icon")); // NOI18N
        openMenuItem.setText(resourceMap.getString("openMenuItem.text")); // NOI18N
        openMenuItem.setName("openMenuItem"); // NOI18N
        openMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                openMenuItemActionPerformed(evt);
            }
        });
        fileMenu.add(openMenuItem);

        cleanTableMenuItem.setText(resourceMap.getString("cleanTableMenuItem.text")); // NOI18N
        cleanTableMenuItem.setName("cleanTableMenuItem"); // NOI18N
        cleanTableMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cleanTableMenuItemActionPerformed(evt);
            }
        });
        fileMenu.add(cleanTableMenuItem);

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(competitiongenerator.CompetitionGeneratorApp.class).getContext().getActionMap(CompetitionGeneratorView.class, this);
        exitMenuItem.setAction(actionMap.get("quit")); // NOI18N
        exitMenuItem.setIcon(resourceMap.getIcon("exitMenuItem.icon")); // NOI18N
        exitMenuItem.setName("exitMenuItem"); // NOI18N
        fileMenu.add(exitMenuItem);

        jMenuItem1.setText(resourceMap.getString("jMenuItem1.text")); // NOI18N
        jMenuItem1.setName("jMenuItem1"); // NOI18N
        jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem1ActionPerformed(evt);
            }
        });
        fileMenu.add(jMenuItem1);

        jMenuItem2.setText(resourceMap.getString("jMenuItem2.text")); // NOI18N
        jMenuItem2.setName("jMenuItem2"); // NOI18N
        jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem2ActionPerformed(evt);
            }
        });
        fileMenu.add(jMenuItem2);

        jMenuItem3.setText(resourceMap.getString("jMenuItem3.text")); // NOI18N
        jMenuItem3.setName("jMenuItem3"); // NOI18N
        fileMenu.add(jMenuItem3);

        jMenuItem4.setText(resourceMap.getString("jMenuItem4.text")); // NOI18N
        jMenuItem4.setName("jMenuItem4"); // NOI18N
        fileMenu.add(jMenuItem4);

        menuBar.add(fileMenu);

        helpMenu.setText(resourceMap.getString("helpMenu.text")); // NOI18N
        helpMenu.setName("helpMenu"); // NOI18N

        aboutMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N
        aboutMenuItem.setName("aboutMenuItem"); // NOI18N
        helpMenu.add(aboutMenuItem);

        menuBar.add(helpMenu);

        statusPanel.setName("statusPanel"); // NOI18N

        statusPanelSeparator.setName("statusPanelSeparator"); // NOI18N

        statusMessageLabel.setName("statusMessageLabel"); // NOI18N

        statusAnimationLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        statusAnimationLabel.setName("statusAnimationLabel"); // NOI18N

        progressBar.setName("progressBar"); // NOI18N

        javax.swing.GroupLayout statusPanelLayout = new javax.swing.GroupLayout(statusPanel);
        statusPanel.setLayout(statusPanelLayout);
        statusPanelLayout.setHorizontalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(statusPanelSeparator, javax.swing.GroupLayout.DEFAULT_SIZE, 551, Short.MAX_VALUE)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(statusMessageLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 377, Short.MAX_VALUE)
                .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(statusAnimationLabel)
                .addContainerGap())
        );
        statusPanelLayout.setVerticalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addComponent(statusPanelSeparator, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(statusMessageLabel)
                    .addComponent(statusAnimationLabel)
                    .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(3, 3, 3))
        );

        setComponent(mainPanel);
        setMenuBar(menuBar);
        setStatusBar(statusPanel);
    }// </editor-fold>//GEN-END:initComponents

    /**
     * Event Manager.
     * @param evt the event.
     */
    private void openMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_openMenuItemActionPerformed
        open();
}//GEN-LAST:event_openMenuItemActionPerformed

    /**
     * Clean table manager.
     * @param evt the event.
     */
    private void cleanTableMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cleanTableMenuItemActionPerformed

        for (int w = 0; w < ExcelTable.getColumnCount(); w++) {
            for (int h = 0; h < ExcelTable.getRowCount(); h++) {
                ExcelTable.setValueAt(null, w, h);
            }
        }

    }//GEN-LAST:event_cleanTableMenuItemActionPerformed

    private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem2ActionPerformed
        ExcelTable.removeColumn(ExcelTable.getColumnModel().getColumn(ExcelTable.getColumnCount() - 1));
}//GEN-LAST:event_jMenuItem2ActionPerformed

    private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed
        ExcelTable.addColumn(new TableColumn());
}//GEN-LAST:event_jMenuItem1ActionPerformed

    /**
     * Manager.
     * @param evt the event
     */
    /**
     * Manager.
     * @param evt the event
     */
    private FileFilter createFileFilter(String description,
            boolean showExtensionInDescription, String... extensions) {
        if (showExtensionInDescription) {
            description = createFileNameFilterDescriptionFromExtensions(
                    description, extensions);
        }
        return new FileNameExtensionFilter(description, extensions);
    }

    private String createFileNameFilterDescriptionFromExtensions(
            String description, String[] extensions) {
        String fullDescription = (description == null) ? "(" : description + " (";
        // build the description from the extension list
        fullDescription += "." + extensions[0];
        for (int i = 1; i < extensions.length; i++) {
            fullDescription += ", .";
            fullDescription += extensions[i];
        }
        fullDescription += ")";
        return fullDescription;
    }

    /**
     * Function Called to open a model file.
     */
    public void open() {

        
        busyIconTimer.start();
        progressBar.setVisible(true);

        // File Chooser Build
        JFileChooser filechooser = new JFileChooser();
        // Open Type
        filechooser.setDialogType(JFileChooser.OPEN_DIALOG);
        // Creating filters for files and adding it to the file chooser
        FileFilter excel_97_2003 = createFileFilter("Excel 97-2003 ",
                true, "xls");
        FileFilter excel_2007 = createFileFilter("Excel Open Format 2007 ",
                true, "xslx");
        filechooser.addChoosableFileFilter(excel_97_2003);
        // Comming soon...
        /* filechooser.addChoosableFileFilter(excel_2007); */
        filechooser.setCurrentDirectory(new File("./src/competitiongenerator/resources"));

        File file = null;
        int retval = filechooser.showDialog(this.getComponent(), null);
        if (retval == JFileChooser.APPROVE_OPTION) {
            file = filechooser.getSelectedFile();
            if (logger.isLoggable(Level.INFO)) {
                logger.info("Selected File: " + file.getName());
            }
        } else if (retval == JFileChooser.CANCEL_OPTION) {
            JOptionPane.showMessageDialog(this.getComponent(), "User cancelled operation. No file was chosen.");
        } else if (retval == JFileChooser.ERROR_OPTION) {
            JOptionPane.showMessageDialog(this.getComponent(), "An error occured. No file was chosen.");
        } else {
            JOptionPane.showMessageDialog(this.getComponent(), "Unknown operation occured.");
        }
        
        if(logger.isLoggable(Level.INFO)){
            logger.log(Level.INFO, "Progress Bar: "+progressBar.getPercentComplete());
        }
        FileInputStream fis = null;
        try {
            if (null != file) {
                fis = new FileInputStream(file);
                TabbedPane.setTitleAt(0, "Competitors ("+file.getName()+")");
            }
        } catch (FileNotFoundException ex) {
            CompetitionGeneratorApp.logger.log(Level.SEVERE, null, ex);
        }
        try {
            if (fis != null) {
                POIFSFileSystem fs = new POIFSFileSystem(fis);
                HSSFWorkbook wb = new HSSFWorkbook(fs);
                HSSFSheet sheet = wb.getSheetAt(0);
                HSSFRow row;
                HSSFCell cell;

                int rows; // Number of rows
                rows = sheet.getPhysicalNumberOfRows();

                int cols = 0; // Number of columns
                int tmp = 0;

                // This trick ensures that we get the data properly even if it doesn't start from first few rows
                for (int i = 0; i < 10 || i < rows; i++) {
                    row = sheet.getRow(i);
                    if (row != null) {
                        tmp = sheet.getRow(i).getPhysicalNumberOfCells();
                        if (tmp > cols) {
                            cols = tmp;
                        }
                    }
                }

                if (CompetitionGeneratorApp.logger.isLoggable(Level.INFO)) {
                    final StringBuffer sb = new StringBuffer();
                    sb.append("Cols: ");
                    sb.append(cols);
                    sb.append("\tRows: ");
                    sb.append(rows);
                    sb.append("\n");
                    CompetitionGeneratorApp.logger.log(Level.INFO, sb.toString());
                }

                for (int r = 0; r < rows; r++) {
                    row = sheet.getRow(r);
                    if (row != null) {
                        for (int c = 0; c < cols; c++) {
                            cell = row.getCell(c);
                            if (cell != null) {
                                // Your code here

                                /* Trying to obtain the cell formula in a cell
                                 * tooltip but doesn't seem to work in that way.
                                 **/
//                                if (cell.getCellFormula().equalsIgnoreCase(null)) {
//                                    ExcelTable.setValueAt(cell.getNumericCellValue()+"", r, c);
//                                } else {
                                ExcelTable.setValueAt(cell, r, c);
//                                }
                            }
                        }
                    }
                }
            } else {
                if(logger.isLoggable(Level.WARNING)){
                    logger.log(Level.WARNING, "File NOT FOUND!!");
                }
            }
            busyIconTimer.stop();
            progressBar.setVisible(false);
            TabbedPane.setEnabled(true);
            CompetitorsPane.setEnabled(true);
            ExcelTable.setEnabled(true);
            FightsPane.setEnabled(true);
        } catch (Exception ioe) {
            logger.log(Level.SEVERE, ioe.toString());
        }
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JScrollPane CompetitorsPane;
    private javax.swing.JTable ExcelTable;
    private javax.swing.JScrollPane FightsPane;
    private javax.swing.JTabbedPane TabbedPane;
    private javax.swing.JMenuItem cleanTableMenuItem;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JMenuItem jMenuItem2;
    private javax.swing.JMenuItem jMenuItem3;
    private javax.swing.JMenuItem jMenuItem4;
    private javax.swing.JPanel mainPanel;
    private javax.swing.JMenuBar menuBar;
    private javax.swing.JMenuItem newMenuItem;
    private javax.swing.JMenuItem openMenuItem;
    private javax.swing.JProgressBar progressBar;
    private javax.swing.JLabel statusAnimationLabel;
    private javax.swing.JLabel statusMessageLabel;
    private javax.swing.JPanel statusPanel;
    // End of variables declaration//GEN-END:variables
    private final Timer messageTimer;
    private final Timer busyIconTimer;
    private final Icon idleIcon;
    private final Icon[] busyIcons = new Icon[15];
    private int busyIconIndex = 0;
    private JDialog aboutBox;
}
